from django.template import Node,Library,TemplateSyntaxError
from iptables.models import Rule

register=Library()

class GetRuleOptions(Node):
    """ Retrns true if it has the mentioned rule"""
    
    def __init__(self,option_list):
        """ The constructor"""
        proto=option_list[0]
        rule_id=option_list[1]
        
    def render(self,context):
        """ That one shows the actual result"""
        try :
            r = Rule.objects.get(id=rule_id)
        
        except Rule.DoesNotExist:
            return False
        
        if proto == "tcp":
            if r.tcp_set.all():
                return True
        
        elif proto=="udp":
            if r.udp_set.all():
                return True
                
        elif proto=="optional":
            if r.optional_set.all():
                return True
         
        #icmp will be here after that one    
        #elif proto =="icmp":
        return False    
            
def is_option(parser,token):
    """ Takes as an arguman tcp,udp,option,icmp and rule id"""
    bits=token.split_contents()
    
    if len(bits)!=3:
        raise TemplateSyntaxError,"is_option 3 arguman alir"
    
    return GetRuleOptions([bits[1][1:-1],bits[2]])
    
#registering all the stuff    
is_option = register.tag(is_option)